import { h } from 'vue';

import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { isFunction } from '@vben/utils';
import type { Recordable } from '@vben/types';

import { ElButton, ElImage, ElSwitch, ElTag, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { MoreFilled } from '@element-plus/icons-vue';

import { useVbenForm } from './form';
import { $t } from '#/locales';


import { IconifyIcon } from '@vben/icons';
import { $te } from '@vben/locales';
import { get, isString } from '@vben/utils';

import { objectOmit } from '@vueuse/core';



setupVbenVxeTable({
  configVxeTable: (vxeUI) => {
    vxeUI.setConfig({
      grid: {
        align: 'center',
        border: false,
        columnConfig: {
          resizable: true,
        },
        minHeight: 180,
        formConfig: {
          // 全局禁用vxe-table的表单配置，使用formOptions
          enabled: false,
        },
        proxyConfig: {
          autoLoad: true,
          response: {
            result: 'items',   // API返回的items字段名
            total: 'totalCount', // API返回的totalCount字段名
            list: 'items',    // 兼容性字段映射
          },
          showActiveMsg: true,
          showResponseMsg: false,
        },
        round: true,
        showOverflow: true,
        size: 'small',
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellImage' },
    vxeUI.renderer.add('CellImage', {
      renderTableDefault(_renderOpts, params) {
        const { column, row } = params;
        const src = row[column.field];
        return h(ElImage, { src, previewSrcList: [src] });
      },
    });

    // 表格配置项可以用 cellRender: { name: 'CellLink' },
    vxeUI.renderer.add('CellLink', {
      renderTableDefault(renderOpts) {
        const { props } = renderOpts;
        return h(
          ElButton,
          { size: 'small', link: true },
          { default: () => props?.text },
        );
      },
    });

    // 添加 CellSwitch 渲染器
    vxeUI.renderer.add('CellSwitch', {
      renderTableDefault({ attrs, props }, { column, row }) {
        const loadingKey = `__loading_${column.field}`;
        const finallyProps = {
          'active-text': $t('common.enabled'),
          'inactive-text': $t('common.disabled'),
          'active-value': 1,
          'inactive-value': 0,
          'inline-prompt': true,
          width: 60,
          ...props,
          modelValue: row[column.field],
          loading: row[loadingKey] ?? false,
          'onUpdate:modelValue': onChange,
        };

        async function onChange(newVal: any) {
          row[loadingKey] = true;
          try {
            const result = await attrs?.beforeChange?.(newVal, row);
            if (result !== false) {
              row[column.field] = newVal;
            }
          } finally {
            row[loadingKey] = false;
          }
        }
        return h(ElSwitch, finallyProps);
      },
    });

    // 添加 CellTag 渲染器用于显示不同类型的标签
    vxeUI.renderer.add('CellTag', {
      renderTableDefault({ options, props }, { column, row }) {
        const cellValue = row[column.field];
        let label = String(cellValue);
        let type = 'info';

        // 处理mappingData配置，用于映射字段值到标签配置
        if (props?.mappingData && Array.isArray(props.mappingData)) {
          // 查找匹配当前字段的配置项
          const matchItem = props.mappingData.find(
            item => item[column.field] === cellValue
          );
          if (matchItem) {
            label = matchItem.label || label;
            type = matchItem.type || type;
          }
        } else {
          // 使用传入的选项来匹配标签配置
          const tagOptions = options ?? [
            { color: 'success', label: $t('common.enabled'), value: 1 },
            { color: 'danger', label: $t('common.disabled'), value: 0 },
          ];
          const tagItem = tagOptions.find((item) => item.value === cellValue);

          // 如果找到了匹配的选项，则使用其配置
          if (tagItem) {
            label = tagItem.label || label;
            type = tagItem.color || type;
          }
        }

        // 渲染标签
        return h(
          ElTag,
          {
            type: type as 'success' | 'warning' | 'info' | 'primary' | 'danger',
            size: 'small',
            ...objectOmit(props || {}, ['mappingData']),
          },
          { default: () => label }
        );
      },
    });

    // 添加自定义操作按钮渲染器
    vxeUI.renderer.add('ActionButtons', {
      renderTableDefault(_renderOpts, params) {
        const { row, column } = params;

        // 简化处理，不再尝试使用renderOpts.options
        return h('div', { class: 'flex justify-center gap-2' }, [
          h(ElButton, {
            size: 'small',
            link: true,
            onClick: () => console.log('操作按钮未配置操作', row)
          }, () => '操作')
        ]);
      }
    });

    /**
     * 注册表格的操作按钮渲染器
     * @description 用于渲染表格的操作列，支持主操作按钮和更多操作下拉菜单
     * @example
     * ```ts
     * // 在列配置中使用
     * {
     *   cellRender: {
     *     name: 'CellOperation',
     *     attrs: {
     *       onClick: (params) => {
     *         // params.code: 'edit' | 'delete'
     *         // params.row: 当前行数据
     *       },
     *       // 主要按钮 - 直接显示
     *       mainButtons: ['edit', 'delete'],
     *       // 所有操作按钮
     *       buttons: [
     *         { code: 'edit', text: '编辑' },
     *         { code: 'delete', text: '删除' },
     *         { code: 'other', text: '其他操作' }
     *       ]
     *     }
     *   }
     * }
     * ```
     */
    vxeUI.renderer.add('CellOperation', {
      renderTableDefault({ attrs, options }, { row }) {
        // 定义操作按钮类型
        type OperationButton = {
          code: string;
          text: string;
          type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default';
          link?: boolean;
          size?: 'large' | 'default' | 'small';
        };

        // 定义默认操作按钮的配置
        const defaultOperations: OperationButton[] = [
          {
            code: 'edit',
            text: $t('common.edit'),
            type: 'primary',
            link: true,
            size: 'small'
          },
          {
            code: 'delete',
            text: $t('common.delete'),
            type: 'danger',
            link: true,
            size: 'small'
          }
        ];

        // 使用传入的buttons配置或options或默认操作按钮
        const operations = (attrs?.buttons || options || defaultOperations) as OperationButton[];

        // 主要按钮（默认为编辑和删除）- 这些按钮会直接显示
        const mainButtonCodes = attrs?.mainButtons || ['edit', 'delete'];

        // 分离主操作按钮和下拉菜单操作按钮
        const mainButtons = operations.filter(btn => mainButtonCodes.includes(btn.code));
        const dropdownButtons = operations.filter(btn => !mainButtonCodes.includes(btn.code));

        // 渲染操作按钮和下拉菜单
        return h('div', { class: 'flex gap-2 justify-center items-center' }, [
          // 主操作按钮
          ...mainButtons.map((opt: OperationButton) =>
            h(ElButton, {
              type: opt.type || 'primary',
              link: opt.link !== false,
              size: opt.size || 'small',
              onClick: () => attrs?.onClick?.({ code: opt.code, row }),
            }, () => opt.text)
          ),

          // 更多操作下拉菜单（仅当有额外操作时显示）
          dropdownButtons.length > 0 ?
            h(ElDropdown, {
              trigger: 'click',
              splitButton: false,
              size: 'small'
            }, {
              default: () => h('div', { class: 'flex items-center cursor-pointer' }, [
                h(ElButton, {
                  type: 'primary',
                  size: 'small',
                  text: true,
                }, () => [
                  h('span', {}, '更多'),
                  h(MoreFilled, { class: 'ml-1' })
                ])
              ]),
              dropdown: () => h(ElDropdownMenu, {}, {
                default: () => dropdownButtons.map(btn =>
                  h(ElDropdownItem, {
                    onClick: () => attrs?.onClick?.({ code: btn.code, row })
                  }, { default: () => btn.text })
                )
              })
            }) : null
        ]);
      },
    });
  },
  useVbenForm,
});

export { useVbenVxeGrid };

export type * from '@vben/plugins/vxe-table';

export type OnActionClickParams<T = Recordable<any>> = {
  code: string;
  row: T;
};
export type OnActionClickFn<T = Recordable<any>> = (
  params: OnActionClickParams<T>,
) => void;
